package demo.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 用来测试远程调用
 *
 * @author yexi
 */
@Configuration
public class RestTemplateConfiguration {

    /**
     * {@code @LoadBalanced}: 标注在 RestTemplate 或者一个 WebClient 的bean上以配置使用 LoadBalancerClient 执行请求
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(3000);
        simpleClientHttpRequestFactory.setReadTimeout(3000);
        RestTemplate restTemplate = new RestTemplate(simpleClientHttpRequestFactory);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.ALL);
        for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
            HttpMessageConverter<?> httpMessageConverter = restTemplate.getMessageConverters().get(i);
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter sc = (StringHttpMessageConverter) httpMessageConverter;
                sc.setWriteAcceptCharset(true);
                sc.setDefaultCharset(StandardCharsets.UTF_8);
            }
            if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {
                try {
                    MappingJackson2HttpMessageConverter mc = (MappingJackson2HttpMessageConverter) httpMessageConverter;
                    mc.setSupportedMediaTypes(mediaTypeList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return restTemplate;
    }

}